<template>
  <div class="wrap" ref="wrap" v-loading="loading">
    <div ref="box" class="box" @mouseenter="mouseenter" @mouseleave="mouseleave">
      <div ref="marquee" class="marquee">{{text}}</div>
    </div>
    <div ref="node" class="node">{{text}}</div>
  </div>
</template>
<script>
export default {
  name : 'Marquee',
  props: {
    lists: {// 父组件传入数据， 数组形式 [ "通知公告1","通知公告2"]
      type:Array,
      default:()=>{
        return []
      }
    },
    speed:{
      type:Number,
      default: 10
    }
  }, 
  data () {
    return {
      text: '', // 数组文字转化后的字符串,
      timer: null,
      loading: true
    }
  },
  created(){
    for (let i = 0; i < this.lists.length; i++) {
      this.text += ' ' + this.lists[i]
    }
  },
  methods: {
    move () {
      // 获取文字text 的计算后宽度  （由于overflow的存在，直接获取不到，需要独立的node计算）
      // let width = this.$refs.node.getBoundingClientRect().width
      let clientWidth = this.$refs.node.clientWidth
      let initWidth = this.$refs.wrap.clientWidth
      let distance = initWidth // 位移距离
      // 设置位移
      this.timer = setInterval(() => {
        distance = distance - 1
        // 如果位移超过文字宽度，则回到起点
        if (-distance >= clientWidth) {
          distance = initWidth
        }
       try{
          this.$refs.box.style.transform = 'translateX(' + distance + 'px)'
       }catch{
         clearInterval(this.timer)   
         this.timer = null
       }
      }, this.speed)
    },
  },
  // 更新的时候运动
  updated: function () {
    // this.move()
  },
  mounted() {
   this.$nextTick(()=>{
    setTimeout(() => {
      this.loading = false
      this.move()
    }, 700);
   })
  },
  unmounted() {
    clearInterval(this.timer)   
    this.timer = null
  },
  watch:{
    lists:{
      handler(){
         for (let i = 0; i < this.lists.length; i++) {
            this.text += ' ' + this.lists[i]
          }
      }
    }
  }
}
</script>
<style scoped>

.wrap {
  overflow: hidden;
  padding: 5px 0;
  width: 100%;
}
.box {
  width: 80000%;
}
.box div {
  float: left;
}
.node {
  position: absolute;
  z-index: -999;
  top: -999999px;
}
.marquee{
  color: #555;
}
</style>

